#include "Game.h"

Game::Game(DandyTanks *Form, QApplication* application): m_form(Form)
{
    QDesktopWidget *d = QApplication::desktop();
    m_form->setFixedHeight(d->height());
    m_form->setFixedWidth(d->width());
    m_scenManager = NULL;
    m_clientManager = NULL;
    m_serverManager = NULL;

    m_scenManager = new SceneManager(m_form->rect());
    //соединение сигналов со слотами для менеджера меню
    m_scenManager->ConnectMenis();

    QObject::connect(m_scenManager,SIGNAL(signalChanged(MenyScene*)), m_form,SLOT(mastchange(MenyScene*)));
    //создание сервера при выборе серверного варианта игры
    QObject::connect(m_scenManager,SIGNAL(signalCreateServer(QString)), this,SLOT(slotCreateServer(QString)));

    //сигнал начала игры
    QObject::connect(m_scenManager,SIGNAL(signalGameStart()), m_form,SLOT(StartGame()));
    QObject::connect(m_scenManager,SIGNAL(signalGameStart()),this, SLOT(slotServerModGameStart()));
    //запуск в режиме клиента
    QObject::connect(m_scenManager,SIGNAL(signalClientGameConnect(QString,QString,QString)),
                     this, SLOT(slotClientModGameStart(QString,QString,QString)));
    // завершить игру при нажатии Esc
    QObject::connect(m_scenManager,SIGNAL(signalPresEscKey()),this,SLOT(slotEscGame()));

    //выход из программы
    QObject::connect(m_scenManager,SIGNAL(signalEnd()), application ,SLOT(closeAllWindows()));
    m_form->SetScreen(m_scenManager->GetScene(0));
}

Game::~Game()
{
    if(m_scenManager != NULL)
    {
       m_scenManager->~SceneManager();
    }

    if(m_clientManager != NULL)
    {
       m_clientManager->~ClientManager();
    }

    if(m_serverManager != NULL)
    {
       m_serverManager->~ServerManager();
    }
}
// создание сервера
void Game::slotCreateServer(QString nick)
{
    //QObject::connect(m_serverManager,SIGNAL(signalst(QStringList)),this,SLOT(slotGetPlayList(QStringList)));
    QFile tankPositionsFile("pos.txt");
    QVector<int> tankStartPos;
    if ( tankPositionsFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug() << "reading pos.txt";
        QTextStream pos(&tankPositionsFile);
        QString positions = pos.readAll();
        QString delimetr = "\n";
        while(1)
        {
            int p = positions.indexOf(delimetr);
            if (p == -1)
            {
                break;
            }
            tankStartPos.push_back(positions.left(p).toInt());
            positions.remove(0, p + 1);
        }
    }

    for (int i = 0; i < tankStartPos.count(); ++i)
        qDebug() << tankStartPos[i];

    m_serverManager = new ServerManager(nick,m_scenManager->GetScene(3),tankStartPos);

    QString S;
    QFile file("map.txt");

    if (file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QTextStream in(&file);
        S = in.readAll();

        QObject::connect(m_form,SIGNAL(CreateMap(int, int, const  QString& ,int ,int ,int , int)),
                         m_serverManager,SLOT(slotCreateMap(int,int, const QString&,int,int,int,int)));
        m_form->CreateMap(S);
    }
}

void Game::slotRejected(QString)
{
    qDebug() << "rejected";
}

void Game::slotAccepted(int)
{
    qDebug() << "accepted";
}

//запуск игры в режиме сервера
void Game::slotServerModGameStart()
{
    QObject::connect(m_serverManager,SIGNAL(signalGameOver(int)),m_form,SLOT(GameOver(int)));

    QObject::connect(m_form, SIGNAL(signalStartGame()),m_serverManager,SLOT(slotStart()));
    m_form->StartGame();

    QObject::connect(m_scenManager,SIGNAL(signalPresKey(QKeyEvent*)), m_serverManager,SLOT(slotKeyPresEvent(QKeyEvent*)));
    timer = new QTimer() ;
    connect(timer, SIGNAL(timeout()), m_serverManager, SLOT(slotUpdate()));
    timer->start(1000 / 33);
}

//создание клиента
void Game::slotClientModGameStart(QString ip, QString port, QString nick)
{

    if (m_clientManager != NULL)
    {
        delete m_clientManager;
    }

    m_clientManager = new ClientManager(ip, port.toInt(), m_scenManager->GetScene(3));
    QObject::connect(m_clientManager,SIGNAL(signalPlaylist(QStringList)),this,SLOT(slotGetPlayList(QStringList)));

    Sleep(500);
    qDebug()<<"send Nick "<< nick;
    QObject::connect(this,SIGNAL(signalSendNick(QString)),m_clientManager,SLOT(slotSetNickname(QString)));
    emit signalSendNick(nick);
    connect(m_clientManager, SIGNAL(signalNicknameRejected(QString)),
            this, SLOT(slotRejected(QString)));
    connect(m_clientManager, SIGNAL(signalNicknameAccepted(int)),this, SLOT(slotAccepted(int)));
    connect(m_clientManager,SIGNAL(signalStartClientGame()),m_scenManager,SLOT(slotSetGame()));
    connect(m_clientManager,SIGNAL(signalStartClientGame()),this,SLOT(slotStartClientGame()));
}

void Game::slotGetPlayList(QStringList list)
{
    QLabel *label = m_scenManager->GetCurrentScene()->GetPlayerListLabel();
    //label->clear();
    QString players;
    int i = 0;
    foreach (QString S,list)
    {
        players += S+"    ";
        if(i % 2)
        {
            players+="\n";
        }
        i++;
    }
    qDebug()<< players;

    label->setText(players);
    qDebug()<< "LABEL!!!!!!!"<<label->text();
    m_scenManager->GetCurrentScene()->update();
}

void Game::slotStartClientGame()
{
    /*Sleep(500);
    timer = new QTimer() ;
    connect(timer, SIGNAL(timeout()), m_clientManager, SLOT(slotUpdate()));
    timer->start(1000 / 33);*/

}

void Game::slotEscGame()
{
    QObject::disconnect(timer, SIGNAL(timeout()), m_serverManager, SLOT(slotUpdate()));
    QObject::disconnect(timer, SIGNAL(timeout()), m_clientManager, SLOT(slotUpdate()));
    if(m_clientManager != NULL)
    {
        QObject::connect(this,SIGNAL(signalClientDisconnect()),m_clientManager, SLOT(slotDisconnect()));
        emit signalClientDisconnect();
    }

    m_form->SetScreen(m_scenManager->GetScene(0));
}

